//
//  SFSpreadTextView.m
//  Test
//
//  Created by xueshan1 on 2019/2/14.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "SFSpreadTextView.h"
#import "UIView+Externsion.h"

@interface SFCustomTextView : UITextView

@end

@implementation SFCustomTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
  
        
    }
    return self;
}
- (BOOL)canBecomeFirstResponder{
    return NO;
}


@end

@interface SFSpreadTextView ()<UITextViewDelegate,UIGestureRecognizerDelegate>

@property(nonatomic,strong)SFCustomTextView *textView;
@property(nonatomic,strong)UIButton   *spreadBtn;
@property(nonatomic,assign)BOOL spreadStatus;
@property(nonatomic,assign)BOOL needSpreadBtn;
@property(nonatomic,assign)CGFloat contentHeight;//实际高度
@property(nonatomic,assign)CGSize shrinkStatusSize;//收缩起来的高度
@property(nonatomic,assign)CGSize spreadBtnSize;
@property(nonatomic,strong)NSDictionary *textAttributes;

//富文本
@property(nonatomic,strong)NSMutableAttributedString *attributeStr;

@end

@implementation SFSpreadTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _needSpreadBtn = NO;
        _spreadStatus = YES;
        _needShrink = YES;
        _contentFont = [UIFont systemFontOfSize:20];
        _maxLine = 2;
        _spreadBtnTitle = @"展开";
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    if (!_textView) {
        _textView = [[SFCustomTextView alloc]initWithFrame:self.bounds];
        _textView.delegate = self;
        _textView.editable = NO;// 非编辑状态下才可以点击Url
//        _textView.selectable = NO; //可选择 才可点击url
        _textView.scrollEnabled = NO;
        _textView.showsVerticalScrollIndicator = NO;
        _textView.showsHorizontalScrollIndicator = NO;
        _textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
        _textView.backgroundColor = [UIColor clearColor];
        [self addSubview:_textView];
        
        [self disableTextViewLongPress:_textView];
    }
    
    if (!_spreadBtn) {
        _spreadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_spreadBtn setTitle:_spreadBtnTitle forState:UIControlStateNormal];
        [_spreadBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_spreadBtn addTarget:self action:@selector(spreadBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        _spreadBtn.hidden = YES;
        [self addSubview:_spreadBtn];
        
    }
}


- (void)spreadBtnClicked:(UIButton *)btn{
    NSLog(@"spreadBtnClicked");
   
    if (self.delegate && [self.delegate respondsToSelector:@selector(spreadButtonClicked:)]) {
        [self.delegate spreadButtonClicked:self];
        return;
    }
    
    if (_spreadStatus) {
        [self showShrinkStatusView:_shrinkStatusSize.height];
    }else{
        [self showSpreadStatusView:_contentHeight];
    }
    
}

#pragma mark - reload
- (void)reloadTextView{
    _textView.font = _contentFont;
    _textView.text = _content;
    
    [_spreadBtn setTitle:_spreadBtnTitle forState:UIControlStateNormal];
    _spreadBtn.titleLabel.font = _contentFont;
    
    CGSize constrainedSize = CGSizeMake(self.frame.size.width, 1000);
    _textAttributes = @{NSFontAttributeName:_contentFont} ;

    _spreadBtnSize = [self getSizeWithString:_spreadBtnTitle constrainedSize:CGSizeMake(MAXFLOAT, _contentFont.lineHeight) attributes:_textAttributes];
    _contentHeight = [self getSizeWithString:_content constrainedSize:constrainedSize attributes:_textAttributes].height;
    _shrinkStatusSize = [self getMaxLinesSizeWithString:_content maxLine:_maxLine constrainedSize:constrainedSize attributes:_textAttributes];
  

   //默认收缩
    if (_contentHeight > _shrinkStatusSize.height) {
        _needSpreadBtn = YES;
        [self showShrinkStatusView:_shrinkStatusSize.height];
    }else{
        _needSpreadBtn = NO;
        [self showSpreadStatusView:_contentHeight];
    }
    
    
  
}
//
- (void)showSpreadStatusView:(CGFloat)height{
    _spreadStatus = YES;
    [_spreadBtn setTitle:@"收起" forState:UIControlStateNormal];
    
    if (_needShrink && _needSpreadBtn) {
        height += _contentFont.lineHeight;
        
        _spreadBtn.y = height - _spreadBtnSize.height;
        _spreadBtn.hidden = NO;
    }else{
    
        _spreadBtn.hidden = YES;
    }
    
    self.height = height;
    self.textView.height = height;
    _textView.textContainer.exclusionPaths = @[];
    
    
}
//
- (void)showShrinkStatusView:(CGFloat)height{
    _spreadStatus = NO;
    [_spreadBtn setTitle:_spreadBtnTitle forState:UIControlStateNormal];

    self.height = height;
    self.textView.height = height;
    CGFloat btnWidth = _spreadBtnSize.width + 20;
    CGRect pathRect = CGRectMake(_shrinkStatusSize.width - btnWidth, _shrinkStatusSize.height - _contentFont.lineHeight, btnWidth, _contentFont.lineHeight);
    UIBezierPath *exclusionPagh = [UIBezierPath bezierPathWithRect:pathRect];
    _textView.textContainer.exclusionPaths = @[exclusionPagh];
    
    _spreadBtn.frame = pathRect;
    _spreadBtn.hidden = NO;
}
- (void)setContent:(NSString *)content{
    _content = content;
    
    _attributeStr = [[NSMutableAttributedString alloc]initWithString:self.content];
    
}

//获取几行文字的高度
- (CGSize)getMaxLinesSizeWithString:(NSString *)string maxLine:(NSInteger)maxLine constrainedSize:(CGSize)constrainedSize attributes:(NSDictionary *)attributes{
    NSLayoutManager *manager = [[NSLayoutManager alloc]init];
    
    NSTextStorage *storage = [[NSTextStorage alloc]initWithString:string];
    [storage addLayoutManager:manager];
    [storage addAttributes:attributes range:NSMakeRange(0, string.length)];
    
    NSTextContainer *container = [[NSTextContainer alloc]initWithSize:constrainedSize];
    container.maximumNumberOfLines = maxLine;
    container.lineFragmentPadding = 0;
    [manager addTextContainer:container];
    
    CGRect rect = [manager boundingRectForGlyphRange:NSMakeRange(0, string.length) inTextContainer:container];
    return rect.size;
}

- (CGSize)getSizeWithString:(NSString *)string constrainedSize:(CGSize)constrainedSize attributes:(NSDictionary *)attributesDic{
    
   CGRect rect = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDic context:nil];
    
    return rect.size;
}

#pragma mark - AttributeText
- (void)addColorTextRange:(NSRange)colorRange color:(UIColor *)color{
    if (!_attributeStr) {
        _attributeStr = [[NSMutableAttributedString alloc]initWithString:self.content];
    }
    [_attributeStr addAttribute:NSFontAttributeName value:self.contentFont range:NSMakeRange(0, _attributeStr.length)];
    [_attributeStr addAttribute:NSForegroundColorAttributeName value:color range:colorRange];
    
    self.textView.attributedText = _attributeStr;
    
}

- (void)addLinkTextWithScheme:(NSString *)scheme linkColor:(UIColor *)linkColor inRange:(NSRange)linkRange {
    if (!_attributeStr) {
        _attributeStr = [[NSMutableAttributedString alloc]initWithString:self.content];
    }
    [_attributeStr addAttribute:NSFontAttributeName value:self.contentFont range:NSMakeRange(0, _attributeStr.length)];
    [_attributeStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@://",scheme] range:linkRange];
//    [_attributeStr addAttribute:NSForegroundColorAttributeName value:linkColor range:linkRange];

    self.textView.attributedText = _attributeStr;
    self.textView.linkTextAttributes = @{NSForegroundColorAttributeName:linkColor?:[UIColor blueColor]};
 
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    
    if (URL.scheme.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(spreadTextView:lineText:lineScheme:)]) {
            [self.delegate spreadTextView:self lineText:[self.content substringWithRange:characterRange] lineScheme:URL.scheme];
        }
        
         return NO;
    }

    return YES;
}


//禁用textView的长按选中
- (void)disableTextViewLongPress:(UITextView *)textView{
    for (UIGestureRecognizer *ges in textView.gestureRecognizers) {
        if ([ges isKindOfClass:[UILongPressGestureRecognizer class]]) {
            ges.delegate = self;
        }
    }
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return NO;
}
/*
 return NO;
 同时 textView.editable一定要设置成YES,
 ->可禁用复制粘贴放大(但linkText 不能点击了)
 */
//-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
//    return NO;
//}



@end
